package Presum;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname 连续数组525
 * @Description TODO
 * @Date 2023/2/14 22:08
 * @Created by xjl
 */
public class 连续数组525 {

    public int findMaxLength(int[] nums) {
        int n = nums.length, ans = 0;
        int[] sum = new int[n + 1];
        for (int i = 1; i <= n; i++) {
            sum[i] = sum[i - 1] + (nums[i - 1] == 0 ? -1 : 1);
        }
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 0);
        for (int i = 1; i <= n; i++) {
            int t = sum[i];
            if (map.containsKey(t)) {
                ans = Math.max(ans, i - map.get(t));
            }else {
                map.put(t, i);
            }
        }
        return ans;
    }

    @Test
    public void test() {
        int maxLength = findMaxLength(new int[]{0,0,1,0,0,0,1,1});
        System.out.println(maxLength);
    }
}
